<template>
  <div class="medicine-list">
    <!-- 筛选和排序区域 -->
    <div class="filter-section">
      <el-row :gutter="20" class="mb-4">
        <el-col :span="6">
          <el-select v-model="filterCategory" placeholder="选择分类" clearable @change="handleFilter">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="价格从低到高" value="priceAsc" />
            <el-option label="价格从高到低" value="priceDesc" />
            <el-option label="库存从多到少" value="stockDesc" />
            <el-option label="库存从少到多" value="stockAsc" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索药材名称"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 药材列表 -->
    <div v-else class="medicine-grid">
      <el-empty v-if="medicines.length === 0" description="暂无数据" />
      <div v-else v-for="medicine in medicines" :key="medicine.id" class="medicine-card">
        <el-card :body-style="{ padding: '0px' }" shadow="hover">
          <img :src="medicine.image || '/default-medicine.jpg'" :alt="medicine.name" class="medicine-image">
          <div class="medicine-info">
            <h3 class="medicine-name">{{ medicine.name }}</h3>
            <p class="medicine-price">¥{{ medicine.price }}</p>
            <p class="medicine-description">{{ medicine.description }}</p>
            <div class="medicine-category">分类：{{ medicine.category }}</div>
            <div class="medicine-stock" :class="{ 'low-stock': medicine.stock < 10 }">
              库存：{{ medicine.stock }}
              <el-tag v-if="medicine.stock < 10" type="warning" size="small">库存紧张</el-tag>
            </div>
            <el-button 
              type="primary" 
              :disabled="medicine.stock === 0"
              @click="addToCart(medicine)"
            >
              {{ medicine.stock === 0 ? '暂时缺货' : '加入购物车' }}
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 12, 24, 36]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { getAllMedicines, searchMedicines, getMedicinesByCategory } from '@/api/medicine'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'MedicineList',
  components: {
    Search
  },
  setup() {
    // 数据
    const medicines = ref([])
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(12)
    const searchQuery = ref('')
    const filterCategory = ref('')
    const sortBy = ref('')

    // 分类选项
    const categories = [
      { value: '补气类', label: '补气类' },
      { value: '补血类', label: '补血类' },
      { value: '补养类', label: '补养类' },
      { value: '清热类', label: '清热类' },
      { value: '理气类', label: '理气类' },
      { value: '平肝类', label: '平肝类' }
    ]

    // 获取药材列表
    const fetchMedicines = async () => {
      try {
        loading.value = true
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          name: searchQuery.value,
          category: filterCategory.value,
          sortField: getSortField(),
          sortOrder: getSortOrder()
        }
        const response = await getAllMedicines(params)
        medicines.value = response.data.records || []
        total.value = response.data.total || 0
      } catch (error) {
        console.error('获取药材列表失败:', error)
        ElMessage.error('获取药材列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取排序字段
    const getSortField = () => {
      switch (sortBy.value) {
        case 'priceAsc':
        case 'priceDesc':
          return 'price'
        case 'stockAsc':
        case 'stockDesc':
          return 'stock'
        default:
          return null
      }
    }

    // 获取排序顺序
    const getSortOrder = () => {
      switch (sortBy.value) {
        case 'priceAsc':
        case 'stockAsc':
          return 'asc'
        case 'priceDesc':
        case 'stockDesc':
          return 'desc'
        default:
          return null
      }
    }

    // 处理分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      fetchMedicines()
    }

    // 处理页码改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchMedicines()
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      fetchMedicines()
    }

    // 处理筛选
    const handleFilter = () => {
      currentPage.value = 1
      fetchMedicines()
    }

    // 处理排序
    const handleSort = () => {
      currentPage.value = 1
      fetchMedicines()
    }

    // 添加到购物车
    const addToCart = (medicine) => {
      if (medicine.stock === 0) {
        ElMessage.warning('该药材暂时缺货')
        return
      }
      ElMessage.success(`${medicine.name} 已添加到购物车`)
    }

    // 监听搜索关键词变化
    watch(searchQuery, () => {
      handleSearch()
    })

    onMounted(() => {
      fetchMedicines()
    })

    return {
      medicines,
      loading,
      currentPage,
      pageSize,
      total,
      searchQuery,
      filterCategory,
      sortBy,
      categories,
      handleSizeChange,
      handleCurrentChange,
      handleSearch,
      handleFilter,
      handleSort,
      addToCart
    }
  }
}
</script>

<style scoped>
.medicine-list {
  padding: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.medicine-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.medicine-card {
  transition: transform 0.3s ease;
}

.medicine-card:hover {
  transform: translateY(-5px);
}

.medicine-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}

.medicine-info {
  padding: 15px;
}

.medicine-name {
  margin: 0 0 10px 0;
  font-size: 1.2em;
  color: #333;
  font-weight: bold;
}

.medicine-price {
  color: #e44d26;
  font-size: 1.3em;
  font-weight: bold;
  margin: 0 0 10px 0;
}

.medicine-description {
  color: #666;
  margin: 0 0 10px 0;
  font-size: 0.9em;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.medicine-category, .medicine-stock {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 8px;
}

.low-stock {
  color: #e6a23c;
}

.loading-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-button) {
  width: 100%;
  margin-top: 10px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input) {
  width: 100%;
}
</style> 